﻿using Newtonsoft.Json;
using QWManage.API.AccessToken;
using QWManage.API.GroupChatDetail92122;
using QWManage.API.GroupChatList92120;
using QWManage.DAL;
using QWManage.Forms;
using QWManage.Model;
using QWManage.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace QWManage
{

    public partial class FrmGroup : Form
    {
        private Thread _thread;
        private DataTable _dataTable = new DataTable("退群");
        private int _inGroupsCount = 0;
        private static object _locker = new object();
        private GroupDAL _groupDAL = new GroupDAL();
        private CustomersGroupsDAL _customersGroupsDAL = new CustomersGroupsDAL();
        List<CustomerGroupInfo> _customerGroupInfos_new;

        public FrmGroup()
        {
            InitializeComponent();
            this.FormClosing += (s, e) =>
            {
                if (_thread != null && _thread.IsAlive) _thread.Abort();
            };
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ThreadPool.SetMinThreads(20, 20);
            ThreadPool.SetMaxThreads(100, 100);
            _thread = new Thread(new ThreadStart(workService));
            _thread.Start();
        }
        private void workService()
        {
            try
            {
                Logs.LogMgr.Log("群组采集", "手动开始");
                Stopwatch sw = Stopwatch.StartNew();
                foreach (var toolStripItem in toolStrip.Items)
                {
                    ToolStripButton btn = toolStripItem as ToolStripButton;
                    if (btn != null) btn.Enabled = false;
                }
                lvUsers.Enabled = false;
                string tokenA = TokenA.GetAccessToken();
                GroupChatListArgs args = new GroupChatListArgs();
                //获取客户群列表
                List<string> groupIds = GroupChatListAPI.Invoke(tokenA, args);

                toolStripProgressBar.Value = 0;
                toolStripProgressBar.Minimum = 0;
                toolStripProgressBar.Maximum = groupIds.Count;
                _customerGroupInfos_new = new List<CustomerGroupInfo>();

                //获取客户群详情
                foreach (string groupId in groupIds)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(saveToDataBaseTask), tokenA + "\t" + groupId);
                }

                while (toolStripProgressBar.Value != toolStripProgressBar.Maximum)
                    Thread.Sleep(3000);

                //string json = JsonConvert.SerializeObject(_customerGroupInfos_new);
                //string fn = Path.Combine(Application.StartupPath, "customerGroupInfos.txt");
                //File.WriteAllText(fn, json, Encoding.UTF8);

                //string fn = Path.Combine(Application.StartupPath, "customerGroupInfos.txt");
                //string json = File.ReadAllText(fn, Encoding.UTF8);
                //_customerGroupInfos_new = JsonConvert.DeserializeObject<List<CustomerGroupInfo>>(json);


                DateTime lastUpdate = DateTime.Now;
                toolStripProgressBar.Value = 0;
                toolStripProgressBar.Minimum = 0;
                toolStripProgressBar.Maximum = _customerGroupInfos_new.Count;

                foreach (CustomerGroupInfo customerGroupInfo in _customerGroupInfos_new)
                {
                    customerGroupInfo.LastUpdate = lastUpdate;
                    toolStripProgressBar.Value += 1;
                    _customersGroupsDAL.Add(customerGroupInfo);
                }
                _customersGroupsDAL.UpdateInGroupStatus(lastUpdate);

                CustomerDAL customerDAL = new CustomerDAL();
                HashSet<string> inGroupUserIds = _customersGroupsDAL.GetMemberInGroupHashSet();
                foreach (string exuserid in inGroupUserIds)
                {
                    customerDAL.UpdateQWGroupStatus(exuserid, 2);
                }
                HashSet<string> notInGroupUserIds = _customersGroupsDAL.GetMemberInGroupHashSet(0);
                foreach (string exuserid in notInGroupUserIds)
                {
                    customerDAL.UpdateQWGroupStatus(exuserid, 1);
                }
                new UpdateLogsDAL().Log("企微群", "数据采集");

                Logs.LogMgr.Log("群组采集", $"手动完成，用时 {sw.Elapsed.TotalSeconds} 秒，约 {sw.Elapsed.TotalMinutes} 分钟");
                MessageBox.Show("群数据采集完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                lvUsers.Enabled = true;
                foreach (var toolStripItem in toolStrip.Items)
                {
                    ToolStripButton btn = toolStripItem as ToolStripButton;
                    if (btn != null) btn.Enabled = true;
                }
            }
        }

        private void saveToDataBaseTask(object obj)
        {
            string[] arr = ((string)obj).Split('\t');
            string tokenA = arr[0];
            string chatID = arr[1];
            string groupName = "";
            List<CustomerGroupInfo> memberInfos_temp = GroupChatDetailAPI.InvokePlus(
                tokenA,
                new GroupChatDetailArgs() { chat_id = chatID }, ref groupName);

            _groupDAL.Append(new GroupInfo() { ChatID = chatID, Name = groupName });

            lock (_locker)
            {
                _customerGroupInfos_new.AddRange(memberInfos_temp);
                toolStripProgressBar.Value += 1;
            }
        }


        private void initializeListView()
        {
            lvUsers.Items.Clear();
            lvUsers.VirtualMode = true;
            lvUsers.View = View.Details;
            lvUsers.FullRowSelect = true;
            lvUsers.MultiSelect = true;
            lvUsers.Columns.Clear();
            _dataTable.Columns.Clear();
            lvUsers.VirtualListSize = _dataTable.Rows.Count;
            lvUsers.Invalidate();

            lvUsers.Columns.Add(new ColumnHeader() { Name = "UserID", Text = "UserID", Width = 300 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Name", Text = "名称", Width = 300 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Status", Text = "状态", Width = 300 });


            _dataTable.Columns.Add("UserID", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("Name", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("Status", System.Type.GetType("System.String"));


            // 绑定事件
            lvUsers.RetrieveVirtualItem += ListView_RetrieveVirtualItem;
            lvUsers.ColumnClick += LvUsers_ColumnClick;
        }

        private void loadData2ListView()
        {
            try
            {
                foreach (Control control in this.Controls) { control.Enabled = false; }
                this.Cursor = Cursors.WaitCursor;
                _dataTable.Rows.Clear();
                lvUsers.VirtualListSize = 0;
                lvUsers.Invalidate();
                _inGroupsCount = 0;
                loadDataCustomers();
                lblStatus.Text = $"共 {Common.FormatInt32(_dataTable.Rows.Count)} 条记录，在群有 {Common.FormatInt32(_inGroupsCount)} 条记录" +
                    $"，不在群有 {Common.FormatInt32(_dataTable.Rows.Count - _inGroupsCount)} 条记录";
                lvUsers.VirtualListSize = _dataTable.Rows.Count;
                lvUsers.Invalidate();
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) { control.Enabled = true; }
                this.Cursor = Cursors.Default;
            }
        }

        private void loadDataCustomers()
        {
            CustomersGroupsDAL customersGroupsDAL = new CustomersGroupsDAL();
            List<CustomerGroupInfo> customerGroupInfos = customersGroupsDAL.GetCustomerGroupInfos();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            foreach (CustomerGroupInfo customerGroupInfo in customerGroupInfos)
            {
                if (!dic.ContainsKey(customerGroupInfo.UserID))
                    dic.Add(customerGroupInfo.UserID, customerGroupInfo);
            }
            CustomerDAL customerDAL = new CustomerDAL();
            List<CustomerInfo> customerInfos = customerDAL.GetCustomerInfos();
            foreach (CustomerInfo customerInfo in customerInfos)
            {
                if (!dic.ContainsKey(customerInfo.Exuserid))
                    dic.Add(customerInfo.Exuserid, customerInfo);
            }
            UserDAL userDAL = new UserDAL();
            List<UserInfo> userInfos = userDAL.GetUserInfos();
            foreach (UserInfo userInfo in userInfos)
            {
                if (!dic.ContainsKey(userInfo.UserID))
                    dic.Add(userInfo.UserID, userInfo);
            }

            HashSet<string> hashsetInGroups = customersGroupsDAL.GetMemberInGroupHashSet();
            string keywords = txtKeywords.Text.Trim().ToLower();
            foreach (string key in dic.Keys)
            {
                string userID = key;
                CustomerGroupInfo customerGroupInfo = dic[key] as CustomerGroupInfo;
                CustomerInfo customerInfo = dic[key] as CustomerInfo;
                UserInfo userInfo = dic[key] as UserInfo;
                string Name = "";
                if (customerGroupInfo != null) Name = customerGroupInfo.Name;
                else if (customerInfo != null) Name = customerInfo.Name;
                else Name = userInfo.Name;
                bool flag = false;
                if (!string.IsNullOrEmpty(keywords))
                {
                    if (!string.IsNullOrEmpty(userID) && userID.ToLower().Contains(keywords))
                        flag = true;
                    else if (!string.IsNullOrEmpty(Name) && Name.ToLower().Contains(keywords))
                        flag = true;

                    if (!flag) continue;
                }
                DataRow dr = _dataTable.NewRow();
                dr["UserID"] = userID;
                dr["Name"] = Name;
                if (hashsetInGroups.Contains(userID))
                {
                    dr["Status"] = "在群";
                    _inGroupsCount++;
                }
                else
                {
                    dr["Status"] = "不在群";
                }
                _dataTable.Rows.Add(dr);
            }
        }


        private void LvUsers_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                if (lvUsers.Items.Count == 0) return;
                ColumnHeader ch = lvUsers.Columns[e.Column];
                string orderType = ch.Tag == null ? "" : (string)ch.Tag;
                if (orderType == "" || orderType == "ASC")
                    orderType = "DESC";
                else
                    orderType = "ASC";
                ch.Tag = orderType;
                string fieldName = ch.Name;
                DataTable newTable = _dataTable.Clone();
                DataRow[] drArr = _dataTable.Select("", fieldName + " " + orderType);
                foreach (DataRow dr in drArr)
                {
                    newTable.ImportRow(dr);
                }
                newTable.AcceptChanges();
                _dataTable = newTable;
                lvUsers.VirtualListSize = _dataTable.Rows.Count;
                lvUsers.Invalidate();
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void ListView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            try
            {
                DataRow dr = _dataTable.Rows[e.ItemIndex];
                ListViewItem lvItem = new ListViewItem(dr["UserID"] == DBNull.Value ? "" : dr["UserID"].ToString());
                lvItem.SubItems.Add(dr["Name"] == DBNull.Value ? "" : dr["Name"].ToString());
                lvItem.SubItems.Add(dr["Status"] == DBNull.Value ? "" : dr["Status"].ToString());

                if (lvItem.SubItems[2].Text == "不在群")
                    lvItem.ForeColor = Color.Red;
                e.Item = lvItem;
            }
            catch { e.Item = new ListViewItem(""); }
        }

        private void btnViewGroups_Click(object sender, EventArgs e)
        {
            FrmViewGroups frm = new FrmViewGroups();
            frm.ShowDialog();
        }



        private void btnViewCustomers_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) { control.Enabled = false; }
                this.Cursor = Cursors.WaitCursor;
                initializeListView();
                loadData2ListView();
            }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) { control.Enabled = true; }
                this.Cursor = Cursors.Default;
            }
        }

        private void FrmGroupChat_Load(object sender, EventArgs e)
        {
            txtKeywords.KeyUp += TxtKeywords_KeyUp;
        }

        private void TxtKeywords_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnViewCustomers_Click(sender, e);
        }

        private void lvUsers_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = lvUsers.GetItemAt(e.X, e.Y);
            if (item == null) return;
            DataRow dr = _dataTable.Rows[item.Index];
            string userid = dr["UserID"].ToString();
            FrmGroupsOfCustomer frm = new FrmGroupsOfCustomer(userid);
            frm.ShowDialog();
        }

    }
}

